# -*- coding:utf-8 -*-

import requests
import json
from common import ReadConfig
from common.Log import MyLog

TIME_OUT = ReadConfig.TIMEOUT


class HTTPRequests:
    def __init__(self):
        pass

    @staticmethod
    def post_requests(url, data=None, **kwargs):
        """
        以json格式返回POST请求的响应数据
        :param url:
        :param data:
        :return:
        """
        res = None
        try:
            rep = requests.post(url=url, data=data, timeout=TIME_OUT, **kwargs)
            res = json.dumps(rep.json(), sort_keys=True, indent=4, ensure_ascii=False)
            MyLog().logger.info(r"----- real url:" + rep.url)
        except requests.exceptions.Timeout:
            MyLog().logger.error('Connect Timeout')
        return res

    @staticmethod
    def get_requests(url, data=None, **kwargs):
        """
        返回json dumps后的GET请求的响应数据，请求失败返回None
        :param url:
        :param data:
        :param kwargs: cookies, headers
        :return:str
        """
        res = None
        try:
            rep = requests.get(url=url, params=data, timeout=TIME_OUT, **kwargs)
            res = json.dumps(rep.json(), sort_keys=True, indent=4, ensure_ascii=False)
            MyLog().logger.info(r"----- real url:" + rep.url)
        except requests.exceptions.ConnectTimeout:
            MyLog().logger.error('Connect Timeout')
        return res
